package perso.perso.view.admin.user;

import java.io.IOException;
import java.util.List;

import org.apache.http.client.ClientProtocolException;

import perso.perso.MyAction;
import perso.perso.wsclient.HttpMiddlewareUserWSCall;

public class AddUserAction extends MyAction{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private BeanUser beanUser;
	




	public void setBeanUser(BeanUser beanUser) {
		this.beanUser = beanUser;
	}



	public BeanUser getBeanUser() {
		return beanUser;
	}



	@Override
	public String execute() throws Exception {
		HttpMiddlewareUserWSCall h = new HttpMiddlewareUserWSCall();
		if(beanUser.getId() == null || beanUser.getId().equals(-1)){
			h.addUser(beanUser);
		} else {
			h.updateUser(beanUser);
		}

		return SUCCESS;
	}



	@Override
	public void validate() {

		if(beanUser.getName() == null || beanUser.getName().length() < 1 || "".equals(beanUser.getName())){
			addFieldError( "beanUser.name", "le nom est obligatoire" );
		}
		if(beanUser.getSurname() == null || beanUser.getSurname().length() < 1 || "".equals(beanUser.getSurname())){
			addFieldError( "beanUser.name", "le nom est obligatoire" );
		}
		if((beanUser.getDay() == null || beanUser.getDay().equals(-1))
				|| (beanUser.getMonth() == null || beanUser.getMonth().equals(-1))
				|| (beanUser.getYear() == null || beanUser.getYear().equals(-1))){
			addFieldError( "beanUser.day", "la date de naissance n'est pas valide" );
		}
		
		//recherche du nom
		HttpMiddlewareUserWSCall h = new HttpMiddlewareUserWSCall();
		try {
			
			List<BeanUser> users = h.getAllUsersByFilters(beanUser.getName(), beanUser.getSurname(), beanUser.getBirthday(), beanUser.getIsProfessor());
			if(users != null && users.size() > 0){
				addActionError( "ce user existe deja" );
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
	}



}
